/*
   Copyright 2011 Jason Drake (jadrake75@gmail.com)
 
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
 
       http://www.apache.org/licenses/LICENSE-2.0
 
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package org.javad.components;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.MessageFormat;
import java.text.NumberFormat;

import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.Timer;

@SuppressWarnings("serial")
public class MemoryStatus extends JPanel {
	
	private JProgressBar memoryBar;
	private Timer timer;
	
	final NumberFormat formatter = NumberFormat.getPercentInstance();
	private String msg = null;

	public MemoryStatus() {
		setPreferredSize(new Dimension(75, 18));
		setLayout(new GridLayout(1, 1, 0, 0));
		add(getMemoryBar());
	}

	protected JProgressBar getMemoryBar() {
		if (memoryBar == null) {
			memoryBar = new JProgressBar();
			memoryBar.setStringPainted(true);
			memoryBar.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent e) {
					Runtime.getRuntime().gc();
				}
			});
			msg = ComponentResources.getString("message.memory.tooltip"); //$NON-NLS-1$
			final ActionListener taskPerformer = new ActionListener() {
				public void actionPerformed(ActionEvent evt) {
					long total = Runtime.getRuntime().totalMemory() / UIHelper.MEGA_BYTES;
					long free = Runtime.getRuntime().freeMemory() / UIHelper.MEGA_BYTES;
					long max = Runtime.getRuntime().maxMemory() / UIHelper.MEGA_BYTES;
					float memory = (100.0f * (total - free)) / max;
					getMemoryBar().setValue(Float.valueOf(memory).intValue());
					getMemoryBar().setToolTipText(MessageFormat.format(msg, (total-free), total, max));
					getMemoryBar().setString(formatter.format(memory / 100.0));
				}
			};
			timer = new Timer(1000, taskPerformer);
			timer.setRepeats(true);
			timer.start();
		}
		return memoryBar;
	}

}
